package dao.impl;

import hibernate.HibernateUtil;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import dao.OrdenCompraDAO;
import dominio.OrdenCompra;

public class OrdenCompraDAOImpl implements OrdenCompraDAO {
	
	private static OrdenCompraDAOImpl instancia = null;
	
	private static SessionFactory sf = null;

	private OrdenCompraDAOImpl(){}
	
	public static OrdenCompraDAOImpl getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new OrdenCompraDAOImpl();
		} 
		return instancia;
	}
	
	
	public OrdenCompra findByID(Integer id) {
		OrdenCompra oc = new OrdenCompra();
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx= session.beginTransaction();
		session.load(oc, id);
		tx.commit();
		session.close();
		return oc;
	}
	
	public void grabarOrdenCompra(OrdenCompra oc){
		Session session = sf.openSession();
		session.beginTransaction();
		session.persist(oc);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public void grabarOrdenesCompra(List<OrdenCompra> ordenes){
		Session session = sf.openSession();
		session.beginTransaction();
		for (OrdenCompra ordenCompra : ordenes) {
			session.persist(ordenCompra);	
		}
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	public List<OrdenCompra> getAll() {
		List<OrdenCompra> ordenes;
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx= session.beginTransaction();
		ordenes = session.createQuery("from OrdenCompra").list();
		tx.commit();
		session.close();		
		return ordenes;
	}

}
